from _struct import unpack

import socket, thread, select, time

__version__ = '0.0.1'
BUFLEN = 8192
VERSION = 'Sogou Proxy/' + __version__
HTTPVER = 'HTTP/1.1'

class ConnectionHandler:
    def __init__(self, connection, address, timeout):
        self.client = connection
        self.client_buffer = ''
        self.timeout = timeout
        self.method, self.path, self.protocol = self.get_base_header()
        if self.method == 'CONNECT':
            self.method_CONNECT()
        elif self.method in ('OPTIONS', 'GET', 'HEAD', 'POST', 'PUT',
                             'DELETE', 'TRACE'):
            self.method_others()
        self.client.close()
        self.target.close()

    def get_base_header(self):
        while 1:
            self.client_buffer += self.client.recv(BUFLEN)
            end = self.client_buffer.find('\n')
            if end != -1:
                break
        print '%s' % self.client_buffer[:end]#debug
        data = (self.client_buffer[:end + 1]).split()
        return data

    def method_CONNECT(self):
        self._connect_target(self.path)
        self.client.send(HTTPVER + ' 200 Connection established\n' +
                         'Proxy-agent: %s\n\n' % VERSION)
        self.client_buffer = ''
        self._read_write()

    def method_others(self):
        self.path = self.path[7:]
        i = self.path.find('/')
        host = self.path[:i]
        self._connect_target(host)

        self.client_buffer=self.add_sogou_header(host,self.client_buffer)

        print self.client_buffer
        self.target.send(self.client_buffer)
        self.client_buffer = ''
        self._read_write()

    def add_sogou_header(self, host, buffer):
        x_sogou_auth = "C7FAF4CBB8151A83048014097F4E6945/111/4a6d22c902cd8f6e"
        x_sogou_timestamp = hex(int(time.time()))[2:].rstrip('L').zfill(8)
        buffer = buffer[:-2]+ 'X-Sogou-Auth: %s\r\nX-Sogou-Tag: %s\r\nX-Sogou-Timestamp: %s\r\n\r\n' %\
                  (
                      x_sogou_auth,
                      self.calc_sogou_hash(x_sogou_timestamp, host),
                      x_sogou_timestamp
                      )

        return buffer

    def _connect_target(self, host):
        i = host.find(':')
        if i != -1:
            port = int(host[i + 1:])
            host = host[:i]
        else:
            host = '115.25.216.17'#####################################################   hosts
            port = 80
        (soc_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
        self.target = socket.socket(soc_family)
        self.target.connect(address)

    def _read_write(self):
        time_out_max = self.timeout / 3
        socs = [self.client, self.target]
        count = 0
        while 1:
            count += 1
            (recv, _, error) = select.select(socs, [], socs, 3)
            if error:
                break
            if recv:
                for in_ in recv:
                    data = in_.recv(BUFLEN)
                    if in_ is self.client:
                        out = self.target
                    else:
                        out = self.client
                    if data:
                        out.send(data)
                        count = 0
            if count == time_out_max:
                break


    def calc_sogou_hash(self, t, host):
        s = (t + host + 'SogouExplorerProxy').encode('ascii')
        code = len(s)
        dwords = int(len(s) / 4)
        rest = len(s) % 4
        dddd = str(dwords) + 'i' + str(rest) + 's'
        v = unpack(str(dwords) + 'i' + str(rest) + 's', s)
        for vv in v:
            if(type(vv) == type('i')):
                break
            a = (vv & 0xFFFF)
            b = (vv >> 16)
            code += a
            code = code ^ (((code << 5) ^ b) << 0xb)
            # To avoid overflows
            code &= 0xffffffff
            code += code >> 0xb
        if rest == 3:
            code += ord(s[len(s) - 2]) * 256 + ord(s[len(s) - 3])
            code = code ^ ((code ^ (ord(s[len(s) - 1]) * 4)) << 0x10)
            code &= 0xffffffff
            code += code >> 0xb
        elif rest == 2:
            code += ord(s[len(s) - 1]) * 256 + ord(s[len(s) - 2])
            code ^= code << 0xb
            code &= 0xffffffff
            code += code >> 0x11
        elif rest == 1:
            code += ord(s[len(s) - 1])
            code ^= code << 0xa
            code &= 0xffffffff
            code += code >> 0x1
        code ^= code * 8
        code &= 0xffffffff
        code += code >> 5
        code ^= code << 4
        code = code & 0xffffffff
        code += code >> 0x11
        code ^= code << 0x19
        code = code & 0xffffffff
        code += code >> 6
        code = code & 0xffffffff
        return hex(code)[2:].rstrip('L').zfill(8)


def start_server(host='localhost', port=8080, timeout=60,
                 handler=ConnectionHandler):
    soc = socket.socket(socket.AF_INET)
    soc.bind((host, port))
    print "Serving on %s:%d." % (host, port)#debug
    soc.listen(0)
    while 1:
        thread.start_new_thread(handler, soc.accept() + (timeout,))

if __name__ == '__main__':
    start_server()